import React, { Component } from 'react'

export default class TodoList extends Component {
    constructor(props) {
        super(props)
        this.state = {
            todo: '',
            list: []
        }
    }
    getTodo(e) {
        // console.log(e.target.value)
        this.setState({
            todo: e.target.value
        })
    }
    addTodo() {
        if (this.state.todo == '') {
            alert("输入不能为空")
            return;
        }
        this.setState(_ => ({ list: [..._.list, { id: Date.now(), title: _.todo }] }))
        // setState 异步? 所以第一次点击的时候 输出的list是空值
        // console.log(this.state.list)
        this.setState({ todo: '' })
    }
    delTodo(id) {
        this.setState(todo => ({ list: todo.list.filter((item) => item.id !== id) }))
    }
    addByEnter(e) {
        if (e.keyCode === 13) {
            this.addTodo()
        }
    }
    render() {
        let { todo, list } = this.state
        return (
            // jsx
            < div >
                <input
                    type="text"
                    value={todo}
                    onChange={e => this.getTodo(e)}
                    onKeyUp={(e) => { this.addByEnter(e) }}
                />
                &nbsp;
                <button onClick={(e) => this.addTodo(e)}> 添加</button>
                <div>
                    {
                        list.map((item) => (
                            <div key={item.id}>
                                <li>
                                    {item.id}---{item.title}
                                    <button onClick={() => this.delTodo(item.id)}>删除</button>
                                </li>
                            </div>
                        ))
                    }
                </div>
            </ div>
        )
    }
}